<template>
  <div class="secondStep">
    <div class="upload-tab">
      <div :class="item.id==activeKey ? 'on baseDiv':'baseDiv'" v-for="(item,index) in dataList" :key="index" @click="changeTab(item , index)">
       <p class="inner-title">{{item.showBak1}}</p> 
       <p class="inner-title" style="font-size: 16px">{{item.showBak2}}</p>
      </div>
    </div>
    <el-tabs v-model="activeKey" @tab-click="handleClick" type="border-card">
      <el-tab-pane v-for='(item,index) in dataList' :key='index' :name='item.id' :label="item.showBak"></el-tab-pane>
      <div style="display: flex;justify-content: flex-end;padding-bottom: 6px">
        <div class="activeNotice" v-if="needSave == true"> 请先完善并点击保存 </div>
        <el-button v-if="addOrEdit !== 'view'" type="primary" @click="deleteByRecordsDateIdHandle">保存</el-button>
      </div>
      <div v-for="(item, index) in addFormData" :key='index'>
        <el-form ref="addFormRef" size="mini" :inline="true">
          <el-table tooltip-effect="light" :data="item.examRecordsStationTeacherEntities" class='inline-table custom-table'>
              <el-table-column label="考站" prop="stationName" width="100" align="center">
                  <template slot-scope="scope">
                      <el-form-item size="small" :prop="'examRecordsStationTeacherEntities.' + scope.$index + '.stationName'"
                        :rules="addFormRules.stationName" class="all">
                        {{ scope.row.stationName }}
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="组" prop="team" width="80" align="center">
                  <template slot-scope="scope">
                      <el-form-item size="small" :prop="'examRecordsStationTeacherEntities.' + scope.$index + '.team'"
                        :rules="addFormRules.team" class="all">
                        {{ scope.row.team }}
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="考官" prop="teacherId" min-width="200" align="center">
                  <template slot-scope="scope">
                      <el-form-item size="small" :prop="'examRecordsStationTeacherEntities.' + scope.$index + '.teacherId'"
                        :rules="addFormRules.teacherId" class="all">
                        <el-select :disabled="addOrEdit === 'view'" @focus='teacherChooseFocus(scope.row.teacherId)' v-model="scope.row.teacherId" multiple filterable placeholder="请选择">
                          <el-option
                            v-for="item in teacherOptions"
                            :key="item.id"
                            :label="item.teacherName"
                            :disabled='item.disabled'
                            :value="item.id">
                            <span style="float: left">{{ item.teacherName }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.teacherMobile }}</span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="考题" prop="examinationId" min-width="150" align="center">
                  <template slot-scope="scope">
                      <el-form-item size="small" :prop="'examRecordsStationTeacherEntities.' + scope.$index + '.examinationId'"
                        :rules="addFormRules.examinationId" class="all">
                        <el-select :disabled="addOrEdit === 'view'" @change="examinationChange(scope.row, scope.row.examinationId)" v-model="scope.row.examinationId" multiple filterable placeholder="请选择">
                          <el-option
                            v-for="item in examOptions"
                            :key="item.id"
                            :label="item.examName"
                            :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                  </template>
              </el-table-column>
          </el-table>
        </el-form>
      </div>
      
    </el-tabs>
  </div>
</template>
<script>
import {recordsDetail, saveStationAndTeacher, recordsstationList, deleteByRecordsDateId, checkStation} from '@/api/examTest.js'
import * as examiner from '@/api/examiner.js'
export default{
  props: ['recordsStationOptions', 'examOptions', 'recordsId', 'passwordCheck', 'addOrEdit'],
  data () {
    return {
      activeIndex: '0',
      needSave: false,
      examRecordsEntity: {},
      dataList: [],
      teacherOptions: [],
      activeKey: 0,
      addFormRules: {
        stationName: [{
          required: true,
          message: '请选择考站',
          trigger: 'blur'
        }],
        teacherId: [{
          required: true,
          message: '请选择考官',
          trigger: 'blur'
        }],
        examinationId: [{
          required: true,
          message: '请选择考题',
          trigger: 'blur'
        }]
      },
      addFormData: [
        {
          examRecordsStationTeacherEntities: [
            {
              stationName: [],
              teacherId: [],
              team: '第一组',
              examinationId: []
            }
          ]
        }, {
          examRecordsStationTeacherEntities: [
            {
              stationName: [],
              teacherId: [],
              team: '第一啥地方组',
              examinationId: []
            }
          ]
        }]
    }
  },
  methods: {
    examinationChange (row, examinationId) {
      console.log(row, examinationId)
      // this.addFormData.map(v => {
      //   if (v.examRecordsStationTeacherEntities[0].stationName === row.stationName && v.examRecordsStationTeacherEntities[0].team === row.team) {
      //     v.examRecordsStationTeacherEntities.map(q => {
      //       q.examinationId = examinationId
      //     })
      //   }
      // })
    },
    teacherChooseFocus (val) {
      setTimeout(() => {
        // 获取所有的已选考官库id
        let chooseId = []
        this.addFormData.map(v => {
          v.examRecordsStationTeacherEntities.map(p => {
            chooseId = chooseId.concat(p.teacherId)
          })
        })
        chooseId = [...new Set(chooseId)]
        let newArr = chooseId.filter((item) => !val.includes(item))
        this.teacherOptions.map(q => {
          if (newArr.indexOf(q.id) > -1) {
            q.disabled = true
          } else {
            q.disabled = false
          }
        })
        let aaa = JSON.stringify(this.teacherOptions)
        this.teacherOptions = []
        this.teacherOptions = JSON.parse(aaa)
      }, 100)
    },
    // 获取考官
    getTeacher (teacherPoolId) {
      examiner.studentList({page: 1, limit: 1000, teacherPoolId: teacherPoolId}).then(res => {
        this.teacherOptions = res.data.page.records
      })
    },
    handleClick (val) {
      if (this.needSave) {
        this.$message.warning('请先完善当前考站并保存')
      } else {
        this.activeIndex = Number(val.index)
        this.needSave = false
        this.activeKey = val.name
        this.getRecordsstationList()
      }
    },
    changeTab (item, index) {
      if (this.needSave) {
        this.$message.warning('请先完善当前考站并保存')
      } else {
        this.activeIndex = Number(index)
        this.needSave = false
        this.activeKey = item.id
        this.getRecordsstationList()
      }
    },
    // 点击下一步先校验考站是否全部维护好了
    checkInfoHandle () {
      let params = this.dataList.map(item => {
        return item.id
      })
      checkStation(params).then(res => {
        if (res.data.code === 0) {
          this.$emit('secondHandleEnd')
        }
      })
    },
    // 点击下一步先校验考站是否全部维护好了
    checkInfoHandleNiMing () {
      let params = this.dataList.map(item => {
        return item.id
      })
      checkStation(params).then(res => {
        if (res.data.code === 0) {
          this.$emit('secondHandleEndNiMing')
        }
      })
    },
    // 保存前先删除时间范围的数据
    deleteByRecordsDateIdHandle () {
      let isNext = true
      for (let j = 0; j < this.addFormData.length; j++) {
        for (let m = 0; m < this.addFormData[j].examRecordsStationTeacherEntities.length; m++) {
          let mak = this.addFormData[j].examRecordsStationTeacherEntities[m]
          console.log('mak', mak)
          if ((!mak.teacherId || mak.teacherId.length === 0) || (!mak.examinationId) || mak.examinationId.length === 0) {
            isNext = false
            break
          }
        }
      }
      if (!isNext) {
        this.$message({
          type: 'warning',
          message: '请完善考站信息'
        })
      } else {
        // 校验之后再保存
        deleteByRecordsDateId({id: this.activeKey}).then(res => {
          this.submit()
        })
      }
    },
    getRecordsstationList () {
      // 查看
      console.log('zzzz')
      recordsstationList({id: this.activeKey}).then(res => {
        // 先分组
        let bak = res.data.recordsDateStationAndTeacherDto.stationAndTeachers
        let stationListBak = bak.map(v => {
          return v.examRecordsStationEntity.stationName
        })
        let stationList = [...new Set(stationListBak)].sort((a, b) => parseInt(a.substring(1, 10)) - parseInt(b.substring(1, 10)))
        let paramsBak = []
        stationList.map(a => {
          paramsBak.push({
            stationName: a,
            children: []
          })
        })
        bak.map(q => {
          paramsBak.map(p => {
            if (p.stationName === q.examRecordsStationEntity.stationName) {
              p.children.push(q)
            }
          })
        })
        paramsBak.map(q => {
          q.children = q.children.sort((a, b) => parseInt(a.examRecordsStationEntity.team.substring(1, 10)) - parseInt(b.examRecordsStationEntity.team.substring(1, 10)))
        })
        // start
        this.addFormData = []
        for (let y = 0; y < paramsBak.length; y++) {
          this.addFormData.push({
            examRecordsStationTeacherEntities: paramsBak[y].children
          })
        }
        this.addFormData.map(v => {
          v.examRecordsStationTeacherEntities.map(p => {
            p.stationName = p.examRecordsStationEntity.stationName
            p.id = p.examRecordsStationEntity.id
            p.team = p.examRecordsStationEntity.team
            p.teacherId = p.examRecordsStationTeacherEntities.map(v => {
              return v.teacherId
            })
            p.examinationId = p.stationExaminationEntities.map(v => {
              return v.examinationId
            })
          })
        })
        setTimeout(() => {
          let qwe = JSON.parse(JSON.stringify(this.addFormData))
          this.addFormData = []
          this.addFormData = JSON.parse(JSON.stringify(qwe))
        }, 10)
        // end
        let teacherArr = res.data.recordsDateStationAndTeacherDto.stationAndTeachers
        console.log('teacherArr', teacherArr)
        if (teacherArr.length > 0) {
          // teacherArr.map(w => {
          //   this.addFormData.examRecordsStationTeacherEntities.push({
          //     examinationId: w.examRecordsStationEntity.examinationId,
          //     stationId: w.examRecordsStationEntity.stationId,
          //     teacherId: w.examRecordsStationTeacherEntities.map(r => {
          //       return r.teacherId
          //     })
          //   })
          // })
        } else {
          if (this.activeIndex > 0) {
            // 如果为空，且不是第一个tab，需要去看看上一个tab有没有数据，有的话需要带过来
            this.nextInformation(this.dataList[this.activeIndex - 1].id)
          } else {
            this.needSave = true
            // 多少个考站
            let stationsNum = Number(this.examRecordsEntity.stationNumber)

            // 一个考站多少个组
            this.addFormData = []
            let groupNum = Number(this.dataList[this.activeIndex].teamCount)
            for (let index = 1; index <= stationsNum; index++) {
              this.addFormData.push({
                examRecordsStationTeacherEntities: []
              })
            }
            for (let index = 0; index < this.addFormData.length; index++) {
              for (let k = 0; k < groupNum; k++) {
                this.addFormData[index].examRecordsStationTeacherEntities.push({
                  stationId: `第${index + 1}考站`,
                  stationName: `第${index + 1}考站`,
                  teacherId: [],
                  team: `第${k + 1}组`,
                  examinationId: []
                })
              }
            }
          }
        }
      })
    },
    // 如果上一个没数据的话 需要接着调取这个接口
    nextInformation (id) {
      // 查看
      console.log('备用查看')
      recordsstationList({id}).then(res => {
        console.log('res.data.recordsDateStationAndTeacherDto.stationAndTeachers', res.data.recordsDateStationAndTeacherDto.stationAndTeachers)
        let teacherArr = res.data.recordsDateStationAndTeacherDto.stationAndTeachers
        if (teacherArr.length > 0) {
          this.needSave = true
          // 先分组
          let bak = res.data.recordsDateStationAndTeacherDto.stationAndTeachers
          let stationListBak = bak.map(v => {
            return v.examRecordsStationEntity.stationName
          })
          let stationList = [...new Set(stationListBak)].sort((a, b) => parseInt(a.substring(1, 10)) - parseInt(b.substring(1, 10)))
          let paramsBak = []
          stationList.map(a => {
            paramsBak.push({
              stationName: a,
              children: []
            })
          })
          bak.map(q => {
            paramsBak.map(p => {
              if (p.stationName === q.examRecordsStationEntity.stationName) {
                p.children.push(q)
              }
            })
          })
          paramsBak.map(q => {
            q.children = q.children.sort((a, b) => parseInt(a.examRecordsStationEntity.team.substring(1, 10)) - parseInt(b.examRecordsStationEntity.team.substring(1, 10)))
          })
          // start
          this.addFormData = []
          for (let y = 0; y < paramsBak.length; y++) {
            this.addFormData.push({
              examRecordsStationTeacherEntities: paramsBak[y].children
            })
          }
          this.addFormData.map(v => {
            v.examRecordsStationTeacherEntities.map(p => {
              console.log('zxjjjjjj', p.examRecordsStationTeacherEntities.map(qq => {
                return qq.teacherId
              }))
              p.stationName = p.examRecordsStationEntity.stationName
              p.id = p.examRecordsStationEntity.id
              p.team = p.examRecordsStationEntity.team
              p.teacherId = p.examRecordsStationTeacherEntities.map(qq => {
                return qq.teacherId
              })
              p.examinationId = p.stationExaminationEntities.map(qq => {
                return qq.examinationId
              })
            })
          })
          setTimeout(() => {
            let qwe = JSON.parse(JSON.stringify(this.addFormData))
            this.addFormData = []
            this.addFormData = JSON.parse(JSON.stringify(qwe))
          }, 10)
          // end
        } else {
          this.addFormData = [
            {
              examRecordsStationTeacherEntities: [
                {
                  stationId: [],
                  teacherId: [],
                  team: '第一组',
                  examinationId: []
                }
              ]
            }, {
              examRecordsStationTeacherEntities: [
                {
                  stationId: [],
                  teacherId: [],
                  team: '第哇哈哈组',
                  examinationId: []
                }
              ]
            }
          ]
        }
      })
    },
    // 提交
    submit () {
      let examRecordsDateEntity = {
        id: this.activeKey,
        recordsId: this.recordsId
      }
      let stationAndTeachers = []
      for (let j = 0; j < this.addFormData.length; j++) {
        for (let n = 0; n < this.addFormData[j].examRecordsStationTeacherEntities.length; n++) {
          let mnk = this.addFormData[j].examRecordsStationTeacherEntities[n]
          let examRecordsStationEntity = {}
          // let examName = this.examOptions.filter(k => {
          //   return k.id === mnk.examinationId
          // })[0].examName
          examRecordsStationEntity = {
            stationName: mnk.stationName,
            stationNumber: parseInt(mnk.stationName.substring(1, 10)),
            team: mnk.team
          }
          // 老师
          let examRecordsStationTeacherEntities = []
          mnk.teacherId.map(v => {
            let q = {}
            q.teacherId = v
            q.teacherTeam = mnk.team
            q.teacherName = this.teacherOptions.filter(m => {
              return m.id === v
            })[0].teacherName
            q.recordDateId = this.activeKey
            q.mobile = this.teacherOptions.filter(m => {
              return m.id === v
            })[0].teacherMobile
            examRecordsStationTeacherEntities.push(q)
          })
          // 考站
          let stationExaminationEntities = []
          mnk.examinationId.map(v => {
            let q = {}
            q.examinationId = v
            q.examTeam = mnk.team
            q.examName = this.examOptions.filter(m => {
              return m.id === v
            })[0].examName
            q.recordDateId = this.activeKey
            stationExaminationEntities.push(q)
          })
          stationAndTeachers.push({
            examRecordsStationEntity,
            examRecordsStationTeacherEntities,
            stationExaminationEntities
          })
        }
      }
      console.log(JSON.stringify({examRecordsDateEntity, stationAndTeachers}))
      saveStationAndTeacher({examRecordsDateEntity, stationAndTeachers}).then(res => {
        this.needSave = false
        this.$message({
          type: 'success',
          message: '考站信息保存成功'
        })
        console.log(res)
      })
    },
    // 第二步查看详情
    getRecordsDetail2 () {
      let params = {
        id: this.recordsId
      }
      if (this.passwordCheck !== '') {
        params.password = this.passwordCheck
        params.passwordType = '1'
      } else {
        params.passwordType = '0'
      }
      recordsDetail(params).then(res => {
        this.dataList = res.data.examRecordsDtos[0].examRecordsDates
        this.examRecordsEntity = res.data.examRecordsDtos[0].examRecordsEntity
        this.dataList = this.dataList.sort((a, b) => new Date(a.examStartDate.substring(0, 19)).getTime() - new Date(b.examStartDate.substring(0, 19)).getTime())
        this.dataList.map(val => {
          val.showBak = val.examStartDate.substring(0, 16) + ' ~ ' + val.examEndDate.substring(5, 11)
          val.showBak1 = val.examStartDate.substring(0, 10)
          val.showBak2 = val.examStartDate.substring(11, 16) + ' ~ ' + val.examEndDate.substring(11, 16)
        })
        console.log('this.dataList', this.dataList)
        this.activeKey = this.dataList[0].id
        this.getRecordsstationList()
        this.getTeacher(res.data.examRecordsDtos[0].examRecordsEntity.teacherPoolId)
      })
    },
    pestChange (e, index) {
      let data = this.addFormData.examRecordsStationTeacherEntities[index]
      Object.keys(data).forEach(key => {
        data[key] = e[key]
      })
      this.addFormData.examRecordsStationTeacherEntities[index].productCount = 1
    },
    handleUpdateYes (row) {
      // 拿到上一行数据再往数组中push（）新的数据
      this.addFormData.examRecordsStationTeacherEntities.push({
        stationId: '',
        teacherId: '',
        examinationId: ''
        // stationId: row.stationId,
        // teacherId: row.teacherId,
        // examinationId: row.examinationId
      })
    },
    handleDeleteProduct (row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.addFormData.examRecordsStationTeacherEntities.splice(row.index, 1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>
<style lang='scss'>
.secondStep{
  .el-tabs__header{
    display: none;
  }
}
.activeNotice{
  background: #21d0b6;
  color: rgba(220, 54, 46, 1);
  font-weight: 400;
  height: 30px;
  line-height: 30px;
  padding: 0 16px 0 10px;
  border-radius: 4px;
  animation: moveRightLeft 2s infinite;
  margin-top: 2px;
  margin-right: 6px;
  position: relative;
}
.activeNotice:after{
  content: '';
  height: 10px;
  width: 10px;
  position: absolute;
  right: -4px;
  top: 8px;
  background: #21d0b6;
  transform: rotate(45deg); /* 旋转45度 */
}

/* 定义动画 */
@keyframes moveRightLeft {
  0%, 100% { transform: translateX(0); }
  50% { transform: translateX(-10px); }
}

.upload-tab {
  height: 65px;
  overflow-x: auto;
  border-bottom: #21d0b6 2px solid;
  width: 100%;
  position: relative;
  z-index: 1;
  display: flex;
  width: 100%;
  overflow-x: scroll;
  white-space: nowrap;
  .baseDiv{
    flex-basis: 180px; 
    flex-shrink: 0; 
  }
}
.upload-tab div {
  width: 188px;
  height: 46px;
  display: inline-block;
  text-align: center;
  float: left;
  color: #606264;
  background: url('~@/assets/img/unactive.png')  no-repeat;
  line-height: 46px;
  font-size: 14px;
  margin-right: -16px;
  position: relative;
  z-index: 5;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.upload-tab div .inner-title{
  padding: 0;
  margin: 0;
  height: 18px;
  line-height: 18px;
}
.upload-tab div.on {
  background: url('~@/assets/img/active.png')  no-repeat;
  color: #fff;
}
.upload-tab div:nth-child(1) {
  z-index: 21;
}
.upload-tab div:nth-child(2) {
  z-index: 20;
}
.upload-tab div:nth-child(3) {
  z-index: 19;
}
.upload-tab div:nth-child(4) {
  z-index: 18;
}
.upload-tab div:nth-child(5) {
  z-index: 17;
}
.upload-tab div:nth-child(6) {
  z-index: 16;
}
.upload-tab div:nth-child(7) {
  z-index: 15;
}
.upload-tab div:nth-child(8) {
  z-index: 14;
}
.upload-tab div:nth-child(9) {
  z-index: 13;
}
.upload-tab div:nth-child(10) {
  z-index: 12;
}
.upload-tab div:nth-child(11) {
  z-index: 11;
}
.upload-tab div:nth-child(12) {
  z-index: 10;
}
.upload-tab div:nth-child(13) {
  z-index: 9;
}
.upload-tab div:nth-child(14) {
  z-index: 8;
}
.upload-tab div:nth-child(15) {
  z-index: 7;
}
.upload-tab div:nth-child(16) {
  z-index: 6;
}
.upload-tab div:nth-child(17) {
  z-index: 5;
}
.upload-tab div:nth-child(18) {
  z-index: 4;
}
.upload-tab div:nth-child(19) {
  z-index: 3;
}
.upload-tab div:nth-child(20) {
  z-index: 2;
}
.upload-tab div:nth-child(21) {
  z-index: 1;
}
</style>